<template>
  <Spin :spinning="loading" :tip="tip" wrapperClassName="cus_spin">
    <!-- <button @click="handleReset">重置操作</button> -->
    <EDesigner ref="designerRef" @save="handleSubmit" @refresh="handleRefresh" :key="activeKey" />
  </Spin>
</template>
<script lang="ts" setup>
  import { EDesigner, type PageSchema } from './core';
  import { ref, onMounted, h, defineExpose } from 'vue';
  import { message, Spin } from 'ant-design-vue';
  import {
    getFormGetFormSchemas,
    getFormUpdateFormSchemas,
    checkFormSchemas,
  } from '/@/api/formDesign/formDesign';
  import { useRouter } from 'vue-router';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { currentRoute } = useRouter();
  const designerRef = ref<typeof EDesigner>();
  const loading = ref(false);
  const tip = ref('加载中...');
  const { createMessage, createConfirm } = useMessage();
  const { t } = useI18n();

  // function handleReset () {
  //   designerRef.value!.reset()
  // }

  // function handleSet() {
  //   console.log(JSON.stringify(designerRef.value!.getData()))
  //   const page = { schemas: [{ type: 'page', id: 'root', name: "测试页面", children: [{ label: '文本框222', type: 'input', field: 'input', icon: 'epic-icon-write', isInput: true, componentProps: { defaultValue: '', placeholder: '请输入' }, id: '9wr7dfv9kjc00' }, { label: '选择框', type: 'select', icon: 'epic-icon-xiala', field: 'select', isInput: true, componentProps: { options: [{ label: '选项1', value: '选项1' }, { label: '选项2', value: '选项2' }], placeholder: '请选择' }, id: '4efvesnkhdo00' }, { label: '复选框', type: 'checkbox', icon: 'epic-icon-duoxuan1', field: 'checkbox', isInput: true, componentProps: { defaultValue: [], options: [{ label: '选项1', value: '选项1' }, { label: '选项2', value: '选项2' }], hidden: false, disabled: true }, id: 'ayk2q9c948s00' }], componentProps: { style: { padding: '16px' } } }], script: "const { defineExpose, getComponent } = this;\n\nfunction test (){\n    console.log('test')\n}\n\n// 通过defineExpose暴露的函数或者属性\ndefineExpose({\n test \n})" }
  //   designerRef.value!.setData(page)
  // }
  const script =
    "const { defineExpose, find } = epic;\n\nfunction test (){\n    console.log('test')\n}\n\n// 通过defineExpose暴露的函数或者属性\ndefineExpose({\n test \n})";
  /**
   * 点击保存按钮操作
   * @param e
   */
  async function handleSubmit(e: PageSchema) {
    console.log('handleSubmit', e);
    try {
      let schemas = e.schemas[0].children || [];
      schemas.forEach((item) => {
        if (item.range) {
          if (!item.range.maxV || item.range.maxV == 'NULL') {
            item.range.maxV = '';
          }
        }
        if (item.lenSize && !item.lenSize.maxV) {
          item.lenSize.maxV = '';
        }
      });

      const params = {
        code: currentRoute.value.query.formCode,
        schemas: JSON.stringify(e.schemas),
      };
      loading.value = true;
      tip.value = '保存中...';

      const data = await checkFormSchemas(params);
      if (data.msg) {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          // content: () => h('span', data.msg),
          content: data.msg,
          onOk: async () => {
            await getFormUpdateFormSchemas(params);
            message.success(t('common.opSuccess'));
            // fetch();
          },
        });
      } else {
        await getFormUpdateFormSchemas(params);
        message.success(t('common.opSuccess'));
        // fetch();
      }
    } catch (error) {
      console.error(error);
    } finally {
      loading.value = false;
    }
  }
  const activeKey = ref(1);
  const handleRefresh = () => {
    activeKey.value += 1;
    fetch();
  };

  const fetch = async () => {
    if (currentRoute.value?.query?.formCode) {
      try {
        loading.value = true;
        const res = await getFormGetFormSchemas({ code: currentRoute.value.query.formCode });
        console.log('res', res);
        if (res) {
          res.forEach((item) => {
            if (item.children && item.children.length > 0) {
              item.children.forEach((item) => {
                if (item.componentProps) {
                  item.componentProps.readonlyName = true;
                } else {
                  item.componentProps = {
                    readonlyName: true,
                  };
                }
              });
            }
          });
          const params = {
            schemas: res,
          };
          designerRef.value!.reset();
          designerRef.value!.setData(params);
        }
      } catch (error) {
        console.error(error);
      } finally {
        loading.value = false;
      }
    }
  };
  onMounted(fetch);

  defineExpose({
    handleRefresh,
  });
</script>
<style lang="less" scoped>
  .cus_spin {
    height: 100vh;
    :deep(.ant-spin-container) {
      height: 100%;
    }
    :deep(.ant-spin) {
      max-height: 100%;
    }
  }
</style>
